package info.niwota.ziplock;

import info.niwota.ziplock.zip.CryptoUtils;
import info.niwota.ziplock.zip.ZipUtils;

import java.io.File;
import java.io.IOException;
import java.security.Key;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;

/**
 * @author qiangli
 * 
 */
public class ArchiveFile {

	private boolean locked;

	//private Context ctx;
	private File top;
	private String ext;
	private File zipfile;

	// private String password;

	public ArchiveFile(Context ctx, File top, File zipfile, String ext)
			throws IOException {
		//this.ctx = ctx;
		this.top = top;
		this.zipfile = zipfile;
		this.ext = ext;
		this.locked = zipfile.getName().endsWith(".zip.enc");
	}

	public List<FileItem> list() throws Exception {
		List<FileItem> list = new ArrayList<FileItem> ();
		if (isLocked()) {
			Key key = getKey();
			CryptoUtils.list(top, zipfile, key, ext, null, list);
		} else {
			ZipUtils.list(top, zipfile, ext, null, list);
		}
		return list;
	}

	public List<FileItem> unzip() throws Exception {
		List<FileItem> list = new ArrayList<FileItem> ();
		if (isLocked()) {
			Key key = getKey();
			Key fkey = getTempKey();
			CryptoUtils.unzip(top, zipfile, key, fkey, ext, null, list);
		} else {
			ZipUtils.unzip(top, zipfile, ext, null , list);
		}
		return list;
	}
	
	private Key getKey() throws Exception {
		return KeyStore.getKey();
	}

	private Key getTempKey() throws Exception {
		return KeyStore.getKey();
	}

	public boolean isLocked() {
		return locked;
	}

	public void refresh() {
		//TODO
	}
}
